# -*- coding: utf-8 -*-
import re

import jieba
import jieba.posseg as pseg


class Record:
    def __init__(self):

        jieba.load_userdict("dict/基础字典.txt")
        jieba.load_userdict("dict/街路巷字典.txt")

    def run(self, umap, cut, lookahead, line):
        from .domain import Location

        self.location = Location(line)
        self.address = ""

        if cut:  # 分词模式
            # 默认选取第一个遇到的省，市或者自治区
            for word in jieba.cut(line):
                # 因为jieba对"上海浦东区"的分词会出现问题，所以这里单独处理
                if word == "上海市浦东新区":
                    self.location.setPlace("上海市", SuperMap.CITY)
                    self.location.setPlace("浦东新区", SuperMap.AREA)
                    continue

                word_type = SuperMap.getType(word)

                if word_type:

                    self.location.setPlace(word, word_type)
                else:
                    self.address += word



        else:  # 完整匹配模式
            i = 0
            while i < len(line):
                sub = line[i:]
                word, word_type = SuperMap.getStartsType(sub, lookahead)
                if word_type:
                    i += len(word)
                    self.location.setPlace(word, word_type)
                    continue
                self.address += line[i]
                i += 1

        # 使用jieba对地址进行预处理
        address = self.address
        word = pseg.cut(address)

        self.address = ""
        if_type = False
        if_jlx = ""
        i = 0
        for (item, type) in word:

            if i == 0:
                if not re.findall('[0-9]+', item):
                    if_jlx = item
            i += 1
            # 分词词性为xc则是匹配了街路巷地址
            if type == "xc":

                self.location.setPlace(item, SuperMap.TSRL)
                if_type = True
            elif if_type:

                self.address += item

        # if if_type is False and if_jlx != "":
        #
        #     self.location.setPlace(if_jlx, SuperMap.TSRL)

        if if_type is False:
            self.location.setPlace(address, SuperMap.ADDRESS)
        else:
            self.location.setPlace(self.address, SuperMap.ADDRESS)

        return self.location.pca_map(umap)

    def is_number_cn(self, s):
        """
        如果是中文则返回假，是数字返回真
        :param s:
        :return:
        """
        try:
            ret = self.__find_mh(["零一二三四五六七八九十〇壹贰叁肆伍陆柒捌玖貮两拾号－之西楼区幢队西上下组栋排舍楼弄门队层室"], s)
            if ret["number"] > 1:
                return True
            float(s)
            return True
        except ValueError:
            pass
        try:
            import unicodedata
            unicodedata.numeric(s)
            return True
        except (TypeError, ValueError):
            pass

        return False

    def __find_mh(self, text_arr, text_1):
        """
        模糊查询，返回查询的字符出现的最多的字段。
        :param text_arr:
        :param text_1:
        :return:
        """
        arr_data = []
        for item in text_arr:
            json_data = {
                "text": "",
                "id": "",
                "number": 0
            }
            for item_2 in text_1:

                index = item.find(item_2)
                if index != -1:
                    json_data["text"] = item[1]
                    json_data["id"] = item[0]
                    json_data["number"] += 1
            arr_data.append(json_data)
        self.bubble_sort_pro(arr_data)
        return arr_data[len(arr_data) - 1]

    def bubble_sort_pro(self, our_list):
        """
        数组排序
        :param our_list:
        :return:
        """
        lastExchangeIndex = 0
        sortBorder = len(our_list) - 1  # 无序数组长度
        for _ in range(len(our_list) - 1):
            flag = True  # 循环标记
            for j in range(0, sortBorder):
                if our_list[j]["number"] > our_list[j + 1]["number"]:
                    our_list[j], our_list[j + 1] = our_list[j + 1], our_list[j]
                    flag = False  # 有元素交换，所以不跳出循环
                    lastExchangeIndex = j
            sortBorder = lastExchangeIndex
            if flag:
                break
        return our_list

    def pca_map(self, umap):
        return self.location.pca_map(umap)


'''
负责管理省市区映射信息
'''


class SuperMap:
    from .mappers import area_city_mapper, city_province_mapper, \
        province_country_mapper, rep_areas, \
        lat_lon_mapper

    AREA = "area"
    CITY = "city"
    PROVINCE = "province"
    ADDRESS = "address"
    TSRL = "tsrl"
    rep_area_set = set()

    @classmethod
    def getType(cls, word):
        if cls.area_city_mapper.get(word):
            return cls.AREA
        if cls.city_province_mapper.get(word):
            return cls.CITY
        if cls.province_country_mapper.get(word):
            return cls.PROVINCE

        return ""

    @classmethod
    def getStartsType(cls, sub, lookahead=8):
        # 如果sub字符串的长度超过8，则也只看前八位
        bound = lookahead if len(sub) > lookahead else len(sub)
        # 总是返回匹配到的最长字符串，所以从后往前遍历
        for i in range(bound, 0, -1):
            subsub = sub[:i]
            subtype = cls.getType(subsub)
            if subtype:
                return subsub, subtype
        return "", ""

    # 如果将“北京市”简写作“北京”，则补全“市”字
    @classmethod
    def fillCity(cls, word):
        if word and not word.endswith("市") \
                and not word.endswith("盟") \
                and not word.endswith("地区") \
                and not word.endswith("自治州"):
            return word + "市", True
        return word, False

    # 如果将“重庆省”简写成“重庆”，则补全“省字”
    @classmethod
    def fillProvince(cls, word):
        if word and not word.endswith("市") and not word.endswith("省"):
            if cls.province_country_mapper.get(word + "市"):
                return word + "市", True
            if cls.province_country_mapper.get(word + "省"):
                return word + "省", True
        # 以下区域需要采用特殊的填充策略
        if word and word == '新疆':
            return '新疆维吾尔族自治区', True
        if word and word == '宁夏':
            return '宁夏回族自治区', True
        if word and word == '西藏':
            return '西藏自治区', True
        if word and word == '广西':
            return '广西壮族自治区', True
        return word, False
